using System;
using UnityEngine.UI;
using Cysharp.Threading.Tasks;

namespace GameCore
{
    public class UI_Message : UIBase<UI_Message>, IMessageForm
    {
        public Text title, info;
        public Button confirm, cancel, closeBtn;
        private Action<bool> action;

        // Start is called before the first frame update
        void Start()
        {
            confirm.onClick.AddListener(() =>
            {
                action?.Invoke(true);
                Hide();
            });
            cancel.onClick.AddListener(() =>
            {
                action?.Invoke(false);
                Hide();
            });
            closeBtn.onClick.AddListener(() => Hide());
        }

        public static void Show(string msg) => Global.UI.Message.ShowUI(msg);

        public static void Show(string title, string msg) => Global.UI.Message.ShowUI(title, msg);

        public void ShowUI(string info) => ShowUI(string.Empty, info, null, null);

        public void ShowUI(string title, string info, Action<bool> action, Delegate onBack = null)
        {
            ShowUI(onBack);
            this.title.text = title;
            this.info.text = info;
            this.action = action;
        }

        public async UniTask<bool> ShowUIAsync(string title, string info)
        {
            ShowUI();
            this.title.text = title;
            this.info.text = info;
            var result = false;
            action = (result1) => result = result1;
            while (gameObject.activeSelf)
                await UniTask.Yield();
            return result;
        }
    }
}